#include "timer1_buzzer.h"
#include "gd32f4xx.h"
#include "systick.h"
#include "systick.h"
#include "gd32f4xx_timer.h"
#include "gd32f4xx_rcu.h"

/**
 * PB9<->Buzzer,
 * 复用输出,高电平
 * timer1,channel 1
 * CH1	: PA1,PB3,PB9
 *
 */
void buzzer_timer_config(void)
{
  // 配置引脚
  rcu_periph_clock_enable(RCU_GPIOB);
  gpio_mode_set(GPIOB, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO_PIN_9);
  gpio_af_set(GPIOB, GPIO_AF_1, GPIO_PIN_9); // 选择复用功能1

  // 配置timer1
  rcu_periph_clock_enable(RCU_TIMER1);
  // 倍频到168Mhz
  rcu_timer_clock_prescaler_config(RCU_TIMER_PSC_MUL4);
  // 复位
  timer_deinit(TIMER1);
  // 参数

  timer_parameter_struct tps;
  timer_struct_para_init(&tps);
  // 分频系数
  tps.prescaler = 2800;
  // 周期
  tps.period = 600 - 1;
  // 初始化定时器
  timer_init(TIMER1, &tps);

  // 通道配置
  timer_oc_parameter_struct ocpara;
  timer_channel_output_struct_para_init(&ocpara);
  // 只有高级定时器才有极性
  ocpara.outputstate = (uint16_t)TIMER_CCX_ENABLE;
  // 使用通道1
  timer_channel_output_config(TIMER1, TIMER_CH_1, &ocpara);

  // 通道输出模式
  timer_channel_output_mode_config(TIMER1, TIMER_CH_1, TIMER_OC_MODE_PWM0);

  // ccr
  timer_channel_output_pulse_value_config(TIMER1, TIMER_CH_1, 0);

  // 开启定时器
  timer_enable(TIMER1);
}

/**
 * 通过周期控制蜂鸣器的频率
 * 因为通过ccr,并不能改变频率,
 */
void buzzer_timer_play(uint16_t hz)
{
  uint32_t car = 1000000 / hz / 100 * 6 - 1;
  uint32_t ccr = car * 0.5f;

  timer_parameter_struct tps;
  timer_struct_para_init(&tps);
  tps.prescaler = 2800;
  tps.period = car;
  timer_init(TIMER1, &tps);

  timer_channel_output_pulse_value_config(TIMER1, TIMER_CH_1, ccr);
}

void buzzer_timer_stop(void)
{
  timer_channel_output_pulse_value_config(TIMER1, TIMER_CH_1, 0);
}

void buzzer_timer_test(void)
{
  systick_config();
  buzzer_timer_config();

  while (1)
  {
    buzzer_timer_play(1047);
    delay_1ms(1000);

    buzzer_timer_play(400);
    delay_1ms(1000);

    buzzer_timer_play(547);
    delay_1ms(1000);

    buzzer_timer_play(1000);
    delay_1ms(1000);
  }
}
